var poinvoice = true;
var inv_date_cal = null;
function open_create_poinvoice(){
	u_hideAllSections();
	u_safeShowElement('createpoinvoice_table_container');
	u_safeShowElement('openLinkDiv');
	
	
	poinvoice = true;
	init_invcreate();
	
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_create_poinvoice()";
	navigationStateArray.push(functionPointerObj);
	}
}

function open_create_nonpoinvoice(){
	u_hideAllSections();
	try{
		$("openLinkDiv").style.display = 'none';
	}catch(ex){}
	u_safeShowElement('createpoinvoice_table_container');
	poinvoice = false;
	init_invcreate();
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_create_nonpoinvoice()";
	navigationStateArray.push(functionPointerObj);
	}
	
}

function init_invcreate(){
	dwr.util.setValue('inv_totalamt',0);
	if(poinvoice){
		var ponumarr = new Array();
		ponumarr.push(" ");
		if(poreceived_cache != null && poreceived_cache.length > 0){
			for(var i=0;i<poreceived_cache.length;i++){
				ponumarr.push(poreceived_cache[i].orderNumber);
			}
		}
		
		dwr.util.removeAllOptions("inv_ponum");
		dwr.util.addOptions('inv_ponum', ponumarr);
		$('inv_ponum_lbl').style.display = '';
		$('inv_ponum').style.display = '';
		$('inv_client_sel').style.display = 'none';
		$('inv_client').style.display = '';
		$('poinv_header').style.display = '';
		$('nonpoinv_header').style.display = 'none';
		$('inv_line_details').style.display = '';
		$('nonpoinv_amt_div').style.display = 'none';
		dwr.util.setValue('inv_supplier',"");
		dwr.util.setValue('inv_client',"");
		dwr.util.setValue('inv_remittoloc',"");
		dwr.util.setValue('inv_supploc',"");

	}else{
		getClientsList(usr_comp_cache.companyId);
		$('inv_ponum_lbl').style.display = 'none';
		$('inv_ponum').style.display = 'none';
		$('inv_client_sel').style.display = '';
		$('inv_client').style.display = 'none';
		$('poinv_header').style.display = 'none';
		$('nonpoinv_header').style.display = '';
		$('inv_line_details').style.display = 'none';
		$('nonpoinv_amt_div').style.display = '';
		dwr.util.setValue('inv_supplier',usr_comp_cache.companyName);
		var str = usr_comp_cache.locations[0].addressLine1 + " " + usr_comp_cache.locations[0].addressLine2 + " " + usr_comp_cache.locations[0].city + " " + usr_comp_cache.locations[0].state + " " + usr_comp_cache.locations[0].zip;
		dwr.util.setValue('inv_remittoloc',str);
		dwr.util.setValue('inv_supploc',str);
		dwr.util.setValue('nonpo_invamt_input','');
	}
	
	dwr.util.setValue('inv_num',"");
	dwr.util.setValue('inv_date',"");
	dwr.util.setValue('inv_title',"");
	dwr.util.setValue('inv_pmtterms',"");
	dwr.util.setValue('inv_cf1',"");
	dwr.util.setValue('inv_cf2',"");
	dwr.util.setValue('inv_cf3',"");
	dwr.util.setValue('inv_reqby',usrname);
	dwr.util.setValue('inv_preparedby',usrname);
	dwr.util.setValue('inv_date', format_date(new Date()));
	assignAttachmentComponent("attachmentComponetPlaceHolder3");
	assignCommentsComponent("commentComponetPlaceHolder3");
	dwr.util.setValue('target_comp_comment',"CREATE_INV");
	dwr.util.setValue('target_comp_attachment',"CREATE_INV");
	po_updatePaymentTerm("inv_pmtterms",usr_comp_cache.paymentTerms);
	
	if(inv_date_cal == null){
		inv_date_cal = new JsDatePick({
			useMode:2,
			target:"inv_date",
			dateFormat:"%m/%d/%Y",
			limitToToday:true,
			cellColorScheme:"aqua",
			dateFormat:"%m/%d/%Y",
			imgPath:"/thirdpartyscripts/jsdatepick/img/",
			weekStartDay:1
		});
	}
}

YAHOO.widget.DataTable.textila = function(elLiner, oRecord, oColumn, oData) {
	if(isEmptyString(oData)){
		elLiner.innerHTML = "<input type='text' size='3' value='"+oRecord.getData('lineAmount')+"' id='"+oRecord.getId() + "-input-invamout' onblur='update_invlineamt(this);'>"  ;
	}else{
		var val
		if(Number(oData) > 0){
			val = Number(oRecord.getData('lineAmount')) - Number(oData);
		}else{
			val = oData;
		}
		elLiner.innerHTML = "<input type='text' size='3' value='"+val+"' id='"+oRecord.getId() + "-input-invamout' onblur='update_invlineamt(this);'>" ;
	}
};


function update_invlineamt(inputid){
	var val = inputid.value;
	if(isNaN(Number(val)) || Number(val) < 0){
		alert('Please enter a non-zero number.');
		inputid.value = '0';
		return;
	}
	
	
	var rec = inv_lineyuitable.getRecord(inputid.id.replace('-input-invamout',''));
	if(rec && rec != null){
		var poamt = rec.getData('lineAmount');
		if(Number(poamt) < Number(val)){
			alert('Invoiced Line amount must be less than or equal to the Purchase Order Line amount.');
			return;
		}else{
			inv_lineyuitable.updateCell(rec, inv_lineyuitable.getColumn('invoicedAmount'),val, true);
			//inv_lineyuitable.updateCell(rec, inv_lineyuitable.getColumn('lineAmount'),val, false);
			
			//Total Invoice Amount:
			var total = 0;
			var rst = inv_lineyuitable.getRecordSet();
			for(var k=0;k<rst.getLength();k++){
				var data = rst.getRecord(k);
				if(data.getData('select')){
					total = total + Number(data.getData('invoicedAmount'));
				}
			}
			
			dwr.util.setValue('inv_totalamt',total);
		}
	}
}

var selpoobj= null;

var inv_lineItemReadOnlycolumnDefs = [ {
	key : "orderLineItemNumber",
	label : "Line",
	width : "50px"
	
}, {
	key : "select",
	label : "Select",
	width : "50px",
	formatter: "checkbox"
	
},{
	key : "partNumber",
	label : "Part Number",
	width : "50px"
	
},{
	key : "lineDescription",
	label : "Description",
	width : "50px"
}, {
	key : "quantity",
	label : "Quantity",
	width : "50px"
	
} ,{
	key : "uomSymbol",
	label : "Unit Of Measure",
	width : "50px"
} ,{
	key : "unitPrice",
	label : "Unit Price",
	width : "50px"
} ,{
	key : "invoicedAmount",
	label : "Invoice Line Amount",
	width : "50px",
	formatter: YAHOO.widget.DataTable.textila
} ,{
	key : "unitCurrencySymbol",
	label : "Currency",
	width : "50px"
},{
	key : "lineAmount",
	label : "Total",
	width : "50px"
} , ];




function inv_selPo(){
	var ponum = dwr.util.getValue('inv_ponum');
	if(poreceived_cache != null && poreceived_cache.length > 0){
		for(var i=0;i<poreceived_cache.length;i++){
			if(poreceived_cache[i].orderNumber == ponum){
				selpoobj = poreceived_cache[i];
				break;
			}
		}
	}
	
	dwr.util.setValue('inv_supplier',usr_comp_cache.companyName);
	dwr.util.setValue('inv_client',selpoobj.clientNameText);
	var str = selpoobj.supplierLocation.addressLine1 + " " + selpoobj.supplierLocation.addressLine2 + " " + selpoobj.supplierLocation.city + " " + selpoobj.supplierLocation.state + " " + selpoobj.supplierLocation.zip;
	
	dwr.util.setValue('inv_remittoloc',str);
	dwr.util.setValue('inv_supploc',str);

	inv_populateLineItems();
	
}

function open_sel_po_from_inv(){
 var ponum = dwr.util.getValue('inv_ponum');
 if(!isEmptyString(trimString(ponum))){
	 open_sel_po(ponum);
 } else{
	 alert("Please select a PO");
 }
 
}


var inv_lineyuitable = null;
function inv_populateLineItems(){
	
	if(selpoobj != null && selpoobj.orderLineItems != null){
		var invlDataSource = new YAHOO.util.DataSource();
		invlDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		inv_lineyuitable = new YAHOO.widget.DataTable("inv_lineDetails_yuiTable",inv_lineItemReadOnlycolumnDefs,invlDataSource,{});
		inv_lineyuitable.addRows(selpoobj.orderLineItems);
		inv_lineyuitable.unsubscribeAll("checkboxClickEvent");
		inv_lineyuitable.subscribe("checkboxClickEvent", function(oArgs){   
	    	var elCheckbox = oArgs.target;
			var newValue = elCheckbox.checked;
			var record = this.getRecord(elCheckbox);
			var column = this.getColumn(elCheckbox);
			record.setData(column.key,newValue);
				//Total Invoice Amount:
				var total = 0;
				var rst = inv_lineyuitable.getRecordSet();
				for(var k=0;k<rst.getLength();k++){
					var data = rst.getRecord(k);
					if(data.getData('select')){
						total = total + Number(dwr.util.getValue(data.getId() + '-input-invamout'));
					}
				}
				
				dwr.util.setValue('inv_totalamt',total);
	     }); 
	}
}

function createinvoice(){
	
	if(poinvoice){
		 var ponum = dwr.util.getValue('inv_ponum');
		 if(isEmptyString(trimString(ponum))){
			 alert("Please select a PO to create Invoice for.");
			 return;
		 }
	}
	
	if(isNaN(Number(dwr.util.getValue('inv_totalamt'))) || Number(dwr.util.getValue('inv_totalamt')) <= 0){
		alert('Please enter valid invoice amount.');
		return;
	}
	
	var inv = {};
	
	if(poinvoice){
		
		var invli = new Array();
	
		//browse through the yui table.
		var rset = inv_lineyuitable.getRecordSet();
		for(var i=0;i<rset.getLength();i++){
			var rec = rset.getRecord(i);
			if(rec.getData('select')){
				var invlineitem = rec._oData;
				var item = {};
				item.invoiceNumber = dwr.util.getValue('inv_num');
				item.invoiceLineNumber = invlineitem.orderLineItemNumber;
				item.partNumber = invlineitem.partNumber;
				item.quantity = invlineitem.quantity;
				item.unitPrice = invlineitem.unitPrice;
				item.unitCurrency = invlineitem.unitCurrency;
				item.unitOfMeasure = invlineitem.unitOfMeasure;
				item.lineAmount = invlineitem.lineAmount;
				
				invli.push(item);
			}
		}
		
		inv.invoiceLineItems = invli;	
		inv.purchaseOrderNumber = selpoobj.orderNumber;
		inv.clientNameText = dwr.util.getValue('inv_client');
		inv.invoicedToCompany = selpoobj.orderCompany;
	}else{
		if(isEmptyString( dwr.util.getValue('inv_client_sel'))){
			alert('Please select a client for a non-PO Invoice.');
			return;
		}
		inv.clientNameText = $('inv_client_sel').options[$('inv_client_sel').selectedIndex].innerHTML;
		inv.invoicedToCompany = dwr.util.getValue('inv_client_sel');
	}
	inv.supplierInvoiceNumber = dwr.util.getValue('inv_num');
	inv.invoiceNumber = dwr.util.getValue('inv_num');
	inv.invoiceDescription = dwr.util.getValue('inv_title');
	inv.mainSupplierCompnay = usr_comp_cache.companyId;
	inv.remitToSupplierCompany = usr_comp_cache.companyId;
	inv.nonPOInvoice = !poinvoice;
	inv.invoiceDate = new Date();
	inv.invoiceCreateDate = new Date();
	inv.invoiceSubmittedDate = new Date();
	inv.invoiceComposer = usrname;
	inv.invoiceOwener = usrname;
	inv.totalInvoiceAmount = Number(dwr.util.getValue('inv_totalamt'));
	inv.originatingSystem = 'ATSCOII';
	inv.orginatingCompany = usr_comp_cache.companyId;
	inv.customField1 = dwr.util.getValue('inv_cf1');
	inv.customField2 = dwr.util.getValue('inv_cf2');
	inv.customField3 = dwr.util.getValue('inv_cf3');
	inv.supplierNameText = usr_comp_cache.companyName;
	inv.orderPaymentTermId = dwr.util.getValue('inv_pmtterms');
	
	try{
		var poAtchArr = new Array();
		if(attachmentctr > 0){
			for(var ip=0;ip<attachmentctr;ip++){
				if($('poattachments_check'+ip+'').checked){
					poAtchArr.push(dwr.util.getValue('poaattach_id'+ip+''));
				}
			}
		}
		
		if(poAtchArr.length > 0){
			inv.invoiceAttachmentsId = poAtchArr;
		}
		
		
		var pocmtarr = new Array();
		if(pocomments_ctr > 0){
			for(var iq=0;iq<pocomments_ctr;iq++){
				if($('pocomment_check'+iq+'').checked){
					pocmtarr.push(dwr.util.getValue('pocomment_text'+iq+''));
				}
			}
		}
		
		if(pocmtarr.length > 0){
			inv.invoiceComments = pocmtarr;
		}
	}catch(ex){
		
	}
	
	
	//validate
	
	//Submit the invoice.
	var dwrCallMetaData = {
			callback : success_subinvoice,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};

	DWR_Invoice.submitInvoice(inv, dwrCallMetaData);
}

function success_subinvoice(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		alert("Invoice Submitted Successfully.");
		return;
	}

	alert("Invoice could not be submitted. Please try again.");
}